package com.cosina.game.robodefence.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;

import com.cosina.game.robodefence.core.BattleEngine;
import com.cosina.game.robodefence.model.Builder;
import com.cosina.game.robodefence.model.Finger;
import com.cosina.game.robodefence.ui.PxUpper;
import com.cosina.game.robodefence.ui.drawable.DrawManager;

public class GameInfoView extends View{

	private static Rect[] buttonAreas = new Rect[4];
	private int moveDown;
	private final int maxMoveDownPart = 60;
	static {
		for(int i=0; i<4; i++){
			buttonAreas[3-i] = new Rect(395 - 80*i , 235, 475 - 80*i ,310);
		}
	}
	
	public GameInfoView(Context context) {
		super(context);
	}

	@Override
	public void draw(Canvas canvas) {
		if(BattleEngine.status == BattleEngine.Status.over){
			DrawManager.drawGameOver(canvas);
		}else{
			DrawManager.drawDiag(canvas);
			DrawManager.drawMenuItem(canvas,moveDown);
			DrawManager.drawFinger(canvas);
			updateMoveDown();
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(BattleEngine.Status.over == BattleEngine.status){
			return true;
		}
		int x = (int)event.getX();
		int y = (int)event.getY();
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			int[] upgradeItems = Builder.getCurrentBuilderItem();
			if(Finger.isClean()){
				
				for(int i=0; i<upgradeItems.length; i++){
					if(Builder.isCanBuilder(upgradeItems[i])== false){
						continue;
					}
					if(buttonAreas[4-i].contains(x, y)){
						Point location = PxUpper.getUpperPx(x, y);
						Finger.attach(location.x, location.y ,upgradeItems[i]);
						return true;
					}
				}
			}
			
			if(Finger.isUpdating()){
				for(int i=0; i<upgradeItems.length; i++){
					if(buttonAreas[4-i].contains(x, y)){
						Finger.tryUpdate(upgradeItems[i]);
						return true;
					}
				}
			}
		}
		if(event.getAction() == MotionEvent.ACTION_UP){
			if(Finger.isBuying()){
				Finger.tryBuyAndclear();
				return true;
			}
		}else if(event.getAction() == MotionEvent.ACTION_MOVE){
			if(Finger.isBuying()){
				Point location = PxUpper.getUpperPx(x, y);
				Finger.update(location.x, location.y);
				return true;
			}
		}
		return super.onTouchEvent(event);
	}
	
	private void updateMoveDown(){
		if(Finger.isBuying()){
			if(moveDown < maxMoveDownPart){
				moveDown += 5;
				this.postInvalidate();
			}
		}else{
			if(moveDown > 0){
				moveDown -= 5;
				this.postInvalidate();
			}
		}
	}
}
